<?php

namespace Dreamcat\ConfigClient\Impl\Saver;

use Components\Utils\Funcs\FileSystemHelper;
use Dreamcat\ConfigClient\ConfigSaverInterface;
use Dreamcat\ConfigClient\Popo\ConfigResult;
use RuntimeException;

/**
 * laravel保存器
 * @author vijay
 */
class LaravelSaver implements ConfigSaverInterface
{
    /** @var string 缓存目录 */
    private $cacheDir;
    /** @var string env文件路径 */
    private $envFilePath;

    /**
     * LaravelSaver constructor.
     * @param string $cacheDir 缓存目录
     * @param string $envFilePath env文件路径
     */
    public function __construct(string $cacheDir, string $envFilePath)
    {
        if (!FileSystemHelper::mkdir($cacheDir)) {
            throw new RuntimeException("缓存目录无效，{$cacheDir}");
        }
        if (!FileSystemHelper::touchFile($envFilePath)) {
            throw new RuntimeException("env文件路径无效，{$envFilePath}");
        }
        $this->cacheDir = $cacheDir;
        $this->envFilePath = $envFilePath;
    }

    /**
     * @inheritDoc
     */
    public function saveConfig(ConfigResult $configResult): bool
    {
        $key = md5(json_encode($configResult->getAppInfo()));
        return file_put_contents("{$this->cacheDir}/{$key}.cae", serialize($configResult->getConfigurations()));
    }

    /**
     * @inheritDoc
     */
    public function onSaveAll(): void
    {
        $envFile = fopen($this->envFilePath, "w");
        foreach (scandir($this->cacheDir) as $cacheFile) {
            $fullFileName = "{$this->cacheDir}/{$cacheFile}";
            if (!is_file($fullFileName)) {
                continue;
            }
            if (substr($cacheFile, -4) != ".cae") {
                continue;
            }
            $cache = unserialize(file_get_contents($fullFileName));
            $this->outputConfig($envFile, $cache);
        }
        fclose($envFile);
    }

    /**
     * 将配置输出到文件中
     * @param resource $file 要输出的文件
     * @param array $configs 配置
     * @param string $prefix 键的前缀
     */
    private function outputConfig($file, array $configs, string $prefix = "")
    {
        foreach ($configs as $key => $val) {
            $fullKey = "{$prefix}{$key}";
            if (is_array($val)) {
                $this->outputConfig($file, $val, "{$fullKey}.");
            } else {
                fwrite($file, "{$fullKey} = {$val}\n");
            }
        }
    }
}

# end of file
